<?php
/**
 * Created by JetBrains PhpStorm.
 * User: FuXiaoHei
 * Date: 13-4-30
 * Time: 下午3:46
 * To change this template use File | Settings | File Templates.
 */

namespace API\App\Model;

use Hx\App;
use Hx\Request;

class User {

    /**
     * 数据库对象
     * @var \Hx\Db
     */
    private $db;

    /**
     * 构造函数
     */
    public function __construct() {
        $this->db = App::Db();
    }

    public function authorize($user, $password, $expire, $app) {
        $sql = App::Sql('HxSite_User', 'id,user,password,nickName,email,url,avatar,userRole')
            ->where('user = :user')
            ->select();
        $userData = $this->db->query($sql, array('user' => $user));
        if ($userData === false) {
            return -1;
        }
        $password = sha1($user->id . '-' . $password . '-HxMvc');
        if ($userData->password !== $password) {
            return -2;
        }
        unset($userData->password);
        $userData->token = $this->getToken($userData->id, $expire, $app);
        return $userData;
    }

    private function getToken($id, $expire, $app) {
        $expireDate = time() + ($expire * 3600 * 24);
        $token = md5($id . '-' . $expireDate . '-' . $app);
        $sql = App::Sql('HxSite_Token', 'token,createDate,expireDate,userId,appName,appIp,appUserAgent')
            ->insert();
        $this->db->exec($sql, array(
            'token' => $token,
            'createDate' => time(),
            'expireDate' => $expireDate,
            'userId' => $id,
            'appName' => $app,
            'appIp' => Request::$ip,
            'appUserAgent' => Request::$agent
        ));
        return $token;
    }

    public function checkToken($user, $token, $app) {
        $sql = App::Sql('HxSite_Token', 'expireDate,appIp')
            ->where('userId = :user AND token = :token AND appName = :app')
            ->select();
        $tokenData = $this->db->query($sql, array(
            'user' => $user,
            'token' => $token,
            'app' => $app
        ));
        if ($tokenData === false) {
            return false;
        }
        if ($tokenData->expireDate < time()) {
            return -1;
        }
        if ($tokenData->appIp != Request::$ip) {
            return -2;
        }
        return true;
    }

}